#include <string.h>
#include <iostream>
using std::cout;
using std::endl;

class Computer{
public:
    Computer(const char * brand,double price)
        : _brand(new char[strlen(brand) + 1]())
          , _price(price)
    {
        strcpy(_brand,brand);
        cout << "Computer(const char *,double)" << endl;
    }

    //const的意义：1.避免修改右操作数的数据成员
    //2.const引用能够绑定右值，可以复制临时对象
    //
    //引用的意义：如果没有引用，发生第一次拷贝构造时，
    //const Computer rhs = pc;
    //此时符合拷贝构造调用的第二种时机，又会发生拷贝构造
    //const Computer rhs = (rhs)
    Computer(const Computer & rhs)
        : _brand(new char[strlen(rhs._brand) + 1]())
          , _price(rhs._price)
    {
        strcpy(_brand,rhs._brand);
        /* rhs._price = 100; */
        cout << "Computer(const Computer &)" << endl;
    }

    Computer & operator=(const Computer & rhs){
        if(this != &rhs){//1.考虑自复制问题
            delete [] _brand;//2.回收左操作数原本申请的堆空间
            _brand = new char[strlen(rhs._brand) + 1]();//3.深拷贝(复制)
            strcpy(_brand,rhs._brand);
            _price = rhs._price;
            cout << "Computer & operator=" << endl;

        }
        return *this;//4.返回*this
    }

    void print(){
        cout << "brand:" << this->_brand << endl
            << "price:" << this->_price << endl;
    }

    ~Computer(){
        if(_brand){
            delete [] _brand;
            _brand = nullptr;
        }
        cout << "~Computer()" << endl;
    }
private:
    char * _brand;
    double _price;
};

void test0(){
    Computer pc("AUSU",4500);
    Computer pc2 = pc;
    pc.print();
    cout << endl;
    pc2.print();
}

void test1(){
    //这里构造了临时对象，并想把临时对象的数据成员复制给pc
    Computer pc = Computer("Apple",13000);
    pc.print();
}


int main(void){
    test1();
    return 0;
}
